package com.orangelife.mobile.surrounding.fragment;

import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.IntentHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.fragment.PullRefreshBaseFragment;
import com.orangelife.mobile.util.LogE;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.main.activity.MainTablActivity;
import com.orangelife.mobile.surrounding.adapter.SurroundingMerchantAdapter;
import com.orangelife.mobile.surrounding.biz.SurroundHttpBiz;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.surrounding.activity.SearchConditionActivity;
import com.orangelife.mobile.surrounding.entity.MerchantEntity;
import com.orangelife.mobile.surrounding.view.MerClassifyPopWin;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 周边商户
 *
 * @author 绯若虚无
 * @version Orange Life v3.4
 */
public class SurroundingMerchantFragment extends PullRefreshBaseFragment {

    @Bind(R.id.flShoppingCart)
    FrameLayout flShoppingCart;
    /** 购物车的数量 */
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;
    @Bind(R.id.pullListView)
    PullToRefreshListView pullListView;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tvClassify)
    TextView tvClassify;
    @Bind(R.id.topBar)
    RelativeLayout topBar;
    @Bind(R.id.tvLatest)
    TextView tvLatest;
    @Bind(R.id.tvHottest)
    TextView tvHottest;
    @Bind(R.id.llTabBar)
    LinearLayout llTabBar;
    @Bind(R.id.ivDown)
    ImageView ivDown;
    private View homePageView;
    private final String ORDER_LATEST = "1";
    private final String ORDER_HOTTEST = "2";
    String orderBy = ORDER_LATEST;
    String industryConfigID = "";
    private boolean isShowMerType = false;
    //变动的部分；
//    HotGoodsListViewAdapter<List<Map<String, Object>>> adapter;
    SurroundingMerchantAdapter adapter;
    private List<MerchantEntity> data;
    /** 是否被销毁 */
    private boolean isDestroyView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        isDestroyView = false;
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.fragment_periphery_shop,
                    container, false);
            ButterKnife.bind(this, homePageView);
            setAdapter();
            /*手动调用基类1*/
            setXListViewAndEmptyLayoutListener(pullListView, emptyLayout, adapter);
        }else{
            ButterKnife.bind(this, homePageView);
        }
        clearChildView(homePageView);
        setOrderByView();
        showOrderBy();
        industryConfigID = "";
        tvClassify.setText("分类");
        return homePageView;
    }

    /** 显示类型，最新商家/人气最高 */
    private void showOrderBy() {
        if (isShowMerType) {
            ivDown.setBackgroundResource(R.drawable.ic_surrounding_up);
            llTabBar.setVisibility(View.GONE);
        } else {
            ivDown.setBackgroundResource(R.drawable.ic_surrounding_down);
            llTabBar.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.tvClassify, R.id.tvLatest, R.id.tvHottest, R.id.flShoppingCart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvClassify:
                if (isConnected(false)) {
                    showMerTypePopWin();
                } else {
                    ToastHelper.getInstance()._toast("网络不给力");
                }
                break;
            case R.id.tvLatest:/*最新商家*/
                tabOrderByType(R.id.tvLatest);
                break;
            case R.id.tvHottest:/*人气最高*/
                tabOrderByType(R.id.tvHottest);
                break;
            case R.id.flShoppingCart:
                jumpToShoppingCart();
                break;
            case R.id.llSearch:
                //跳转搜索界面
                IntentHelper.getInstances().getIntent(getActivity(), SearchConditionActivity.class);
                break;
        }
    }

    private void jumpToShoppingCart() {
        IntentHelper.getInstances().getIntent(getActivity(), ShoppingCartActivity.class);
    }

    /** 切换排序类型，最新商家或人气最高 */
    private void tabOrderByType(int clickID) {
        currentReqMode = REQ_MODE_INIT;
        pullListView.setSelection(0);
        showProgress();
        if (clickID == R.id.tvLatest) {
            orderBy = ORDER_LATEST;
        } else {
            orderBy = ORDER_HOTTEST;
        }
        setOrderByView();
        requestWhenPullRefresh();
    }

    /** 弹出商家分类弹出框 */
    private void showMerTypePopWin() {
        int bottomHeight = 0;
        try {
            bottomHeight = ((MainTablActivity) getActivity()).mTabHost.getHeight();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MerClassifyPopWin popwin = new MerClassifyPopWin(getActivity(), topBar.getHeight(), bottomHeight);
        LogE.E("topBarHeight = " + topBar.getHeight() + "，mTabHost height = " + bottomHeight);
        popwin.setAnimationStyle(R.style.PopupAnimation);
        popwin.showAsDropDown(topBar);
        popwin.setOnPopupWindowClickListener(new MerClassifyPopWin.OnPopupWindowItemClickListener() {

            @Override
            public void onPopupWindowItemClick(int clickPositon, String strItemData, String industryName) {
                industryConfigID = strItemData;
                tvClassify.setText(industryName);
                requestWhenPullRefresh();
            }

            @Override
            public void onDismiss() {
                isShowMerType = false;
                showOrderBy();
            }
        });
        isShowMerType = true;
        showOrderBy();
    }

    /** 设置切换栏样式 */
    private void setOrderByView() {
        if (orderBy.equals(ORDER_HOTTEST)) {
            tvHottest.setTextColor(getResources().getColor(R.color.lightOrange));
            tvHottest.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            tvLatest.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            tvLatest.setTextColor(getResources().getColor(R.color.homepage_text_black));
        } else if (orderBy.equals(ORDER_LATEST)) {
            tvHottest.setTextColor(getResources().getColor(R.color.homepage_text_black));
            tvLatest.setTextColor(getResources().getColor(R.color.lightOrange));
            tvHottest.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
            tvLatest.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }
    }

    private void setAdapter() {
        data = new ArrayList<>();
        adapter = new SurroundingMerchantAdapter<>(getActivity(), data);
    }

    /** 设置购物车商品数量 */
    private void setShoppingCarNumber() {
        int goodNum = ShoppingCartBiz.getGoodsCount();
        if (goodNum == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(goodNum + "");
        }
    }

    @Override
    protected EmptyLayout getEmptyLayout() {
        return emptyLayout;
    }

    @Override
    protected List getData() {
        return data;
    }

    @Override
    protected int getDataCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    protected void requestWhenPullRefresh() {
        SurroundHttpBiz.getMerchantList(pageNo, pageSize, orderBy, industryConfigID, callback);
    }

    VolleyHttpUtil.ResponseCallBack callback = new VolleyHttpUtil.ResponseCallBack() {
        @Override
        public void handleResponse(JSONObject response, int errCode) {
            if (isDestroyView) {
                return;
            }
             /*手动调用基类3*/
            dismissProgress();
            int total = SurroundHttpBiz.getDataTotal(response);
            List<MerchantEntity> list = SurroundHttpBiz.handleMerchantList(response, errCode);
             /*手动调用基类2*/
            handleAfterRequest(isConnected(false), total, list, pullListView, adapter);
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        isDestroyView = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        setShoppingCarNumber();
        BLog.getInstance().intAppmod(BLog.NEARBY);
    }

    @Override
    public void onStop() {
        super.onStop();
        BLog.getInstance().outAppmod(BLog.NEARBY);
    }
}
